import { createCarApi, getCarPageApi } from '@/apis/car'
import { getOwnerByIdApi } from '@/apis/owner'
import { getParkPageApi } from '@/apis/park'
import {
    createParkRecordApi,
    getLastParkRecordApi,
    getParkRecordByIdApi,
    updateParkRecordApi,
} from '@/apis/parkRecord'
import { getParkSpacePageApi, updateParkSpaceApi } from '@/apis/parkSpace'
import { getGenPayRecordApi } from '@/apis/payRecord'
import dayjs from 'dayjs'
import QRcode from 'qrcode'
import { ref, watch } from 'vue'
import { layer } from './ts'
import { cars } from './ts/Car'
import { drawParkSpaces } from './ts/ParkSpace'
import { leaveDoor, leavePolyline } from './ts/doors'

// 停车场列表
export const parkData = ref<any>(null)
// 当前选中的停车场id
export const selectedPark = ref<any>(null)
// 当前停车位列表，会显示在入口大屏上
export const selectedSpaces = ref<any>(null)
const getParkData = async () => {
    const res = (await getParkPageApi({
        limit: 1000,
    })) as any
    if (res) {
        parkData.value = res.rows
        selectedPark.value = res.rows[0].id
    }
}
getParkData()

export const enterScreen = ref({
    carNum: '', // 车牌号
    carId: undefined, // 车辆id
    ownerName: '', // 车主姓名
    spaceType: 0, // 车位类型
    price: 0, // 公用车位价格
    spaceList: [], // 车位列表
})

watch(selectedPark, async (val) => {
    if (val) {
        // 获取停车位列表
        const res2 = (await getParkSpacePageApi({
            parkId: val,
            limit: 1000,
        })) as any
        // 更新屏幕上的价格
        const price = parkData.value.find((item) => item.id === val).realPrice
        enterScreen.value.price = price

        // 删掉所有的car
        selectedSpaces.value = res2.rows
        cars.forEach((car) => car.remove())
        setTimeout(() => {
            drawParkSpaces(res2.rows, layer)
        }, 300)
    }
})

// 根据车牌号获取车辆信息
const getInfoByCarNum = async (carNum) => {
    const result = {
        carNum, // 车牌号
        carId: undefined, // 车辆id
        ownerName: '', // 车主姓名
        spaceType: 0, // 车位类型
        price: enterScreen.value.price, // 公用车位价格
        spaceList: [], // 车位列表
    }

    // 根据车牌获取车辆id
    const res = (await getCarPageApi({
        carNum,
    })) as any
    // 如果系统中已经有这个车辆直接取id
    if (res.rows.length > 0) {
        result.carId = res.rows[0].id
        // 如果有车主id就获取车主姓名
        if (res.rows[0].ownerId) {
            result.ownerName = res.rows[0].ownerName
            const res2 = (await getOwnerByIdApi(res.rows[0].ownerId)) as any
            // 如果parkId存在，并且没有过期则是私人车位
            if (res2.parkId && dayjs(res2.expireTime).isAfter(dayjs())) {
                result.spaceType = 1
                result.spaceList = [{ number: res2.parkSpaceNumber, status: 0 }]
            } else {
                result.spaceType = 0
                // 获取空闲车位列表
                result.spaceList = selectedSpaces.value
            }
        } else {
            result.spaceType = 0
            // 获取空闲车位列表
            result.spaceList = selectedSpaces.value
        }
    } else {
        // 如果系统中没有则创建
        const res2 = (await createCarApi({
            carNum: carNum,
        })) as any
        result.carId = res2.id
        result.spaceType = 0
        // 获取空闲车位列表
        result.spaceList = selectedSpaces.value
    }

    return result
}

// 刷新入口屏幕
export const updateEnterScreen = async (carNum) => {
    if (enterScreen.value.carNum === carNum) return
    enterScreen.value = await getInfoByCarNum(carNum)
}

// 车辆进入停车场
export const carEnterPark = async (carNum) => {
    // 创建一条停车记录
    const res3 = await createParkRecordApi({
        carId: enterScreen.value.carId,
        parkId: selectedPark.value,
        parkSpaceType: enterScreen.value.spaceType,
        enterTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    })
    console.log('进入成功', res3)
}

export const leaveScreen = ref({
    carNum: '', // 车牌号
    price: 0, // 价格
    spaceType: 0, // 车位类型
    dis: 0, // 停车时长
    hourPrice: 0, // 小时价格
})

let lastParkRecord = null

export const qrCodeInfo = ref({
    img: '',
    url: '',
})

const genQrCode = async (carNum) => {
    if (!carNum) {
        qrCodeInfo.value.img = ''
        qrCodeInfo.value.url = ''
        return
    }
    const { origin, pathname } = window.location
    const url = `${origin + pathname}/#/m/pay?carNum=${carNum}`
    qrCodeInfo.value.url = url
    qrCodeInfo.value.img = await QRcode.toDataURL(url)
}

export const resetLeaveScreen = () => {
    // 清空屏幕
    leaveScreen.value.carNum = ''
    genQrCode('')
    leaveScreen.value.price = 0
    leaveScreen.value.dis = 0
    leaveScreen.value.hourPrice = 0
    leaveScreen.value.spaceType = 0
    lastParkRecord = null
}

// 刷新出口屏幕
export const updateLeaveScreen = async (carNum) => {
    if (leaveScreen.value.carNum === carNum) return
    leaveScreen.value.carNum = carNum
    genQrCode(carNum)
    if (!lastParkRecord || leaveScreen.value.carNum !== carNum) {
        lastParkRecord = await getLastParkRecordApi({
            carNum,
        })
    } else {
        return
    }
    const res = (await getGenPayRecordApi({
        parkId: selectedPark.value,
        parkSpaceType: lastParkRecord.parkSpaceType,
        enterTime: lastParkRecord.enterTime,
        leaveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    })) as any

    leaveScreen.value.price = res.price
    leaveScreen.value.dis = res.dis
    leaveScreen.value.hourPrice = res.hourPrice
    leaveScreen.value.spaceType = lastParkRecord.parkSpaceType

    // 如果是私人车位，直接开门，并更新停车记录
    if (lastParkRecord.parkSpaceType === 1 && res.price === 0) {
        leaveDoor.open()
        await updateParkRecordApi(lastParkRecord.id, {
            leaveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        })
        return
    }

    // 不停的轮询该记录，如果付钱了就开门
    const _askRecord = async () => {
        const res2 = (await getParkRecordByIdApi(lastParkRecord.id)) as any
        console.log(res2)
        if (res2.payRecordStatus === 1) {
            leaveDoor.open()
            return
        }
        // 获取车辆
        const car = cars.find((v) => v.id === leaveScreen.value.carNum)
        console.log(car)
        // 判断它是否还在出口处
        const atLeaveDoor = car.isIn(leavePolyline)
        console.log(atLeaveDoor)
        if (atLeaveDoor) {
            console.log('开启计时器')
            setTimeout(() => {
                console.log('计时器调用了')
                _askRecord()
            }, 2000)
        } else if (leaveScreen.value.carNum === carNum) {
            resetLeaveScreen()
        }
    }
    _askRecord()
}

// 车辆进出停车位
export const carInOutParkSpace = async (parkSpaceId, isIn: boolean) => {
    console.log(11)
    // 如果是进入
    // 从车位列表中找到这个车位
    const parkSpace = selectedSpaces.value.find(
        (item) => item.id === parkSpaceId
    )
    const newStatus = isIn ? 1 : 0
    parkSpace.status = newStatus
    // 发送请求
    updateParkSpaceApi(parkSpaceId, {
        status: newStatus,
    })
}
